import yaml
import os
from pathlib import Path
import datetime
import time
from nonebot import get_driver
import random

global_config = get_driver().config
g = global_config.dict()
adminID = g["admin_id"]

path_sexypict = Path(g["path_sexypict"]).resolve()
path_data = Path(g["path_data"]).resolve()

yaml_name = "pict_info.yaml"
path_yaml = path_sexypict.joinpath(yaml_name)
yaml_data: dict

yaml_title = dict({
    "name": "涩图库配置文件",
    "__version__": "0.0.8",
    "time": {"create_time": "", "edit_time": "", },
    "dir": {"common_dir": [], "special_dir": []},
    "data": {}
})


# In[210]:
def yaml_create():
    yamlfile = path_yaml
    with open(yamlfile, "w+", encoding='utf-8') as f:
        yaml_title["time"]["create_time"] = datetime.datetime.now().__str__()
        yaml.dump(yaml_title, f, allow_unicode=True, sort_keys=False)  # sort_keys是否根据字母改变顺序
        f.close()


def yaml_update():
    global yaml_data
    yamlfile = path_yaml
    f = open(yamlfile, "r+", encoding='utf-8')
    yaml_data = yaml.load(f, Loader=yaml.FullLoader)
    yaml_title["time"]["edit_time"] = datetime.datetime.now().__str__()

    # 更新图片文件夹
    dirs = yaml_update_dir(path_sexypict, yaml_data)
    for _dir in dirs:
        yaml_update_dir_file(_dir, yaml_data)

    f.seek(0)
    yaml.dump(yaml_data, f, allow_unicode=True, sort_keys=False)  # sort_keys 是否根据字母改变顺序
    f.close()


def yaml_update_dir(_root_dir: Path, data: dict):
    # 载入图片文件夹
    ls = []
    common_dir = []
    special_dir = []
    for i in os.listdir(_root_dir):
        if os.path.isdir(path_sexypict.joinpath(i).resolve()):
            ls.append(i)
            if i.startswith("_"):
                special_dir.append(i)
            else:
                common_dir.append(i)
    data["dir"]["common_dir"] = common_dir
    data["dir"]["special_dir"] = special_dir
    return ls


def yaml_update_dir_file(_dir: Path, data: dict):
    # 载入每个文件夹中的图片
    pict_list = []
    for i in os.listdir(path_sexypict.joinpath(_dir).resolve()):
        if i.endswith(".jpg") or i.endswith("png") or i.endswith(".jpeg"):
            pict_list.append(i)
    data["data"][_dir] = pict_list


def yaml_init():
    yamlfile = path_yaml
    if os.path.isfile(yamlfile):
        print("找到yaml配置文件")
        # 检查配置文件
        with open(yamlfile, "r", encoding='utf-8') as f:
            try:
                data = yaml.load(f, Loader=yaml.FullLoader)
                if data["__version__"] == yaml_title["__version__"]:
                    print("版本号符合")
                else:
                    print("版本号不符合")
                    yaml_create()
            except:
                print("读取版本号错误,重新配置")
                yaml_create()
    else:
        print("没有找到yaml配置文件，进行初始化配置")
        yaml_create()

    yaml_update()


def info_image_list():
    global yaml_data
    list_info = []
    str = ""
    for i in yaml_data["dir"]["common_dir"]:
        num = len(yaml_data["data"][i])
        list_info.append(f"{i} : {num}")
    for i in yaml_data["dir"]["special_dir"]:
        num = len(yaml_data["data"][i])
        list_info.append(f"{i} : {num}")
    for i in list_info:
        str = str + "\n" + i
    return str


def get_image(type_pict):
    # 根据类型返回图片绝对路径
    global yaml_data
    if type_pict == "common":
        n = random.choice(yaml_data["dir"]["common_dir"])
    if type_pict == "special":
        n = random.choice(yaml_data["dir"]["special_dir"])

    if len(yaml_data["data"][n]) is not 0:
        nn = random.choice(yaml_data["data"][n])
        return path_sexypict.joinpath(n).joinpath(nn)
    else:
        return 0
